<template>
  <view class="log-detail-page" :style="DynamicHeight">
    <up-navbar :title="`${logObj.add_name}的${logObj.templete_name}`" :autoBack="false" placeholder
      @leftClick="leftClick" class="custom-navbar">
    </up-navbar>

    <!-- 个人信息 -->
    <view class="log-content" :style="tabsDynamicHeight">
      <view class="log-meta" v-if="logObj.add_time">
        <view class="meta-author">
          <image :src="logObj.img_url" class="author-avatar"></image>
          <view class="author-info">
            <text class="author-name">{{ logObj.add_name || '未知用户' }}的{{ (logObj.templete_name || '日志') }}</text>
            <view class="meta-bottom">
              <text class="meta-time">{{ formatTime(logObj.add_time) }} {{ logObj.weekday || '' }}</text>
            </view>
          </view>
        </view>
      </view>

      <!-- 日志信息 -->
      <view class="log-body" v-if="content.length !== 0">
        <view class="log-section" v-for="item in getFieldByType('quill')" :key="item.field_value">
          <text class="section-title">{{ item.field_name }}：</text>
          <view class="task-list">
            <rich-text v-if="item.field_content" :nodes="item.field_content" class="rich-text-content"></rich-text>
            <view v-else>
              -
            </view>
          </view>
        </view>
        <!-- 备注 -->
        <view class="log-section" v-for="item in getFieldByType('textarea')" :key="item.field_value">
          <text class="section-title">{{ item.field_name }}：</text>
          <view class="task-list">
            <rich-text v-if="item.field_content" :nodes="item.field_content" class="rich-text-content"></rich-text>
            <view v-else>
              -
            </view>
          </view>
        </view>
        <!-- 图片 -->
        <view class="log-section" v-if="getFieldByType('image').length && getImageList().length">
          <text class="section-title">图片：</text>
          <view class="image-list">
            <view class="image-item" v-for="(img, idx) in getImageList()" :key="idx">
              <image :src="ProcessingURL(img.url)" mode="widthFix" @click="previewImage(img.url)"></image>
            </view>
          </view>
        </view>
        <!-- 附件 -->
        <view class="log-section" v-if="getFieldByType('file').length && getFileList().length">
          <text class="section-title">附件：</text>
          <view class="file-list">
            <view class="file-item" v-for="(file, idx) in getFileList()" :key="idx" @click="downloadFile(file)">
              <text class="file-icon">{{ isImage(file.name) ? '🖼️' : '📄' }}</text>
              <text class="file-name">{{ file.name }}</text>
            </view>
          </view>
        </view>
      </view>

      <view class="empty-state" v-else>
        <text>暂无日志内容</text>
      </view>

    <!-- 评论区 -->
    <view class="comment-section" v-if="commentList.length">
      <!-- 评论标题 -->
      <view class="comment-title">
        <text class="title-text">评论 ({{ commentList.length }})</text>
      </view>
      <!-- 评论列表 -->
      <view class="comment-list">
        <view class="comment-item" v-for="item in commentList" :key="item.id">
          <!-- 头像 + 用户名 + 时间 -->
          <view class="comment-header">
            <image  :src="item.img_url" class="comment-avatar"></image>
            <view class="comment-meta">
              <text class="comment-name">{{ item.add_name || '匿名用户' }}</text>
              <text class="comment-time">{{ formatTime(item.add_time) }}</text>
            </view>
          </view>
          <!-- 评论内容 -->
          <view class="comment-content">
            <text>{{ item.content || '无内容' }}</text>
          </view>
        </view>
      </view>
    </view>
    </view>
  </view>
</template>

<script>
import { logDetails } from '@/apis/cloud/worklog'
import { useUserStore } from '@/pinia-store/user'
import { mapStores } from 'pinia'
export default {
  name: 'chatLog',
  data () {
    return {
      height: 0,
      DynamicHeight: {},
      tabsDynamicHeight: {},
      logObj: {},
      content: [], // 解析后的content数组
      commentList:[], // 评论数组
      id: '',
      token: '',
      nextCloud: '',
      fileList: []
    }
  },
  async onLoad (e) {
    await this.calcHeight() // 提取高度计算为方法
    this.id = e?.id || ''
    this.token = uni.getStorageSync('token') || this.userStore.user.token
    await this.geTlogDetails()
  },
  computed: {
    ...mapStores(useUserStore),
  },
  created () {
    this.nextCloud = uni.getStorageSync('next_cloud');
  },
  methods: {
    // 筛选类型
    getFieldByType (type) {
      return this.content.filter(item => item.field_type === type)
    },
    // 高度计算逻辑
    calcHeight () {
      const systemInfo = uni.getSystemInfoSync();
      this.height = systemInfo.windowHeight || systemInfo.screenHeight || 0;

      this.DynamicHeight = { height: `${this.height}px`, overflow: 'hidden' };

      // #ifdef APP-PLUS
      this.tabsDynamicHeight = { height: `${this.height - 76}px`, overflow: 'auto' };
      // #endif

      // #ifdef H5
      this.tabsDynamicHeight = { height: `${this.height - 45}px`, overflow: 'auto' };
      // #endif
    },

    // 获取日志详情
    async geTlogDetails () {
      uni.showLoading({ title: '加载中...',mask:true });
      try {
        const res = await logDetails({ id: this.id, token: this.token })
        if (res.status === 1 && res.data[0]) {
          this.logObj = res.data[0] || []
          this.content = JSON.parse(this.logObj.content || '[]')
          this.commentList = JSON.parse(this.logObj.commentList || '[]')
        } else {
          uni.showToast({ title: res.msg || "获取失败", icon: "error" });
        }
      } catch (error) {
        uni.showToast({ title: "获取失败，请重试", icon: "error" });
      } finally {
        uni.hideLoading();
      }
    },

    formatTime (timeStr) {
      if (!timeStr) return ''
      const date = new Date(timeStr)
      return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${date.getHours()}:${date.getMinutes().toString().padStart(2, '0')}`
    },

    getImageList () {
      const imageField = this.getFieldByType('image')[0]
      if (!imageField) return []
      return JSON.parse(imageField.field_content || '[]')
    },

    getFileList () {
      const fileField = this.getFieldByType('file')[0]
      if (!fileField) return []
      this.fileList = JSON.parse(fileField.field_content || '[]')
      return JSON.parse(fileField.field_content || '[]')
    },

    // 预览图片
    previewImage (currentUrl) {
      const imageUrls = this.getImageList().map(img => img.url)
      uni.previewImage({
        current: currentUrl,
        urls: imageUrls
      })
    },

    // 查看附件
    downloadFile (item) {
      // 1. 获取文件后缀
      const ext = (item.name || item.filename).split('.').pop().toLowerCase();

      // 2. 图片处理
      if (['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg'].includes(ext)) {
        // 使用当前组件或页面的文件列表 this.fileList
        const imgList = (this.fileList || [])
          .filter(i => ['png', 'jpg', 'jpeg', 'gif', 'bmp', 'webp', 'svg']
            .includes((i.name || i.filename).split('.').pop().toLowerCase()))
          .map(i => this.ProcessingURL(i.url || i.path) || `${COMMON_API_BASE_URL}${i.path}`);

        const currentUrl = this.ProcessingURL(item.url || item.path) || `${COMMON_API_BASE_URL}${item.path}`;
        const index = imgList.indexOf(currentUrl);
        uni.previewImage({
          current: index >= 0 ? index : 0,
          urls: imgList,
        });
      }
      // 3. 文件处理
      else {
        const strname = item.name || item.filename;
        const strurl = item.url || item.path;
        const type = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf'];
        const str = strname.split('.');
        const icon = str[str.length - 1];
        const that = this;
        let url = '';
        const xtoken = this.nextCloud.xtoken;

        if (type.includes(icon)) {
          let previewUrl = '';

          if (xtoken) {
            previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?xtoken=${xtoken}&nc_id=${item.nc_id ? item.nc_id : ''}&fileName=${strname}&type=mobile&user=${that.userStore.user.worker_id}&url=${strurl}`;
          } else {
            previewUrl = `https://cloud.mfarmers.com/dist/previewDoc1.html?fileName=${strname}&type=mobile&user=${that.userStore.user.worker_id}&url=${strurl}`;
          }

          let encodedData = encodeURIComponent(JSON.stringify({ previewUrl }));
          url = `/pages/chat/message/common/previewDoc?data=${encodedData}`;
        } else {
          url = `/pages/chat/message/common/downloadDoc?fileName=${strname}&fileSize=${item.formatSize}&url=${strurl}`;
        }

        uni.navigateTo({ url });
      }
    },

    ProcessingURL (url) {
      let setUrl = null;
      if (url.startsWith("http://117.89.250.65:81/")) {
        setUrl = url.replace("http://117.89.250.65:81", "https://cloud.mfarmers.com");
      } else if (url.startsWith("https://cloud.mfarmers.com/")) {
        setUrl = url; // 已经是目标域名，无需替换
      } else if (url.startsWith("http://121.229.203.227:81/")) {
        setUrl = url.replace("http://121.229.203.227:81", "https://cloud.mfarmers.com");
      } else {
        setUrl = url; // 如果都不匹配，就保持原样
      }
      return setUrl;
    },
    // 根据文件名获取对应文件类型的图标
    // 检查是否是图片
    isImage (filename) {
      if (!filename) return false;
      const imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'webp'];
      const extension = filename.split('.').pop().toLowerCase();
      return imageExtensions.includes(extension);
    },

    // 返回上一页
    leftClick () {
      uni.navigateBack();
    }
  }
};
</script>

<style lang="scss" scoped>
.log-detail-page {
  width: 100%;
  background-color: #f5f5f7;

  .log-content {
    background-color: #ffffff;
    box-sizing: border-box;
    line-height: 1.6;
    padding: 10rpx 30rpx;

    .log-meta {
      margin-bottom: 30rpx;

      .meta-author {
        display: flex;
        align-items: center;
        margin-bottom: 16rpx;

        .author-avatar {
          width: 80rpx;
          height: 80rpx;
          border-radius: 20%;
          margin-right: 16rpx;
        }

        .author-info {
          align-items: center;

          .author-name {
            font-size: 32rpx;
            font-weight: 600;
            color: #222;
          }

          .log-title {
            font-size: 28rpx;
            color: #666;
            margin-left: 8rpx;
          }

          .meta-bottom {
            display: flex;
            justify-content: space-between;
            align-items: center;

            .meta-time {
              font-size: 24rpx;
              color: #8a8b8c;
            }
          }
        }
      }


    }

    // 主体内容样式
    .log-body {
      .log-section {
        margin-bottom: 20rpx;

        .section-title {
          font-size: 36rpx;
          font-weight: 600;
          color: #191e25;
          display: block;
          margin-bottom: 16rpx;
        }

        .task-list {
          margin-left: 10rpx;
          color: #343536;

          .text-content {
            font-size: 28rpx;
            line-height: 1.8;
          }

          .rich-text-content {
            display: block;
            word-break: break-all;
            overflow-wrap: break-word;
            white-space: normal;
          }

          .rich-text-content>>>p {
            word-break: break-all !important;
            white-space: normal !important;
            overflow-wrap: break-word !important;
            line-height: 1.8;
            font-size: 28rpx;
            margin: 0 0 10rpx 0;
          }
        }

        // 图片列表样式
        .image-list {
          display: flex;
          flex-wrap: wrap;
          gap: 20rpx;

          .image-item {
            width: 200rpx;
            margin-bottom: 10rpx;

            image {
              width: 100%;
              height: 160rpx;
              object-fit: cover;
              border-radius: 8rpx;
              margin-bottom: 8rpx;
            }

            .image-name {
              font-size: 22rpx;
              color: #666;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }
          }
        }

        // 附件列表样式
        .file-list {
          .file-item {
            display: flex;
            align-items: center;
            padding: 16rpx;
            background-color: #f9f9f9;
            border-radius: 8rpx;
            margin-bottom: 16rpx;

            .file-icon {
              font-size: 32rpx;
              color: #007aff;
              margin-right: 16rpx;
            }

            .file-name {
              flex: 1;
              font-size: 26rpx;
              color: #333;
              display: -webkit-box;
              -webkit-line-clamp: 1;
              -webkit-box-orient: vertical;
              overflow: hidden;
            }

            .file-size {
              font-size: 22rpx;
              color: #8a8b8c;
            }
          }
        }
      }
    }

    // 空状态样式
    .empty-state {
      text-align: center;
      padding: 100rpx 0;
      font-size: 28rpx;
      color: #8a8b8c;
    }
  }

  // 评论区整体样式
  .comment-section {
    margin-top: 30rpx;
    padding: 20rpx 0;
    border-top: 1px solid #f0f0f0;

    // 评论标题
    .comment-title {
      margin-bottom: 20rpx;
      .title-text {
        font-size: 30rpx;
        font-weight: 600;
        color: #222;
      }
    }

    // 评论列表
    .comment-list {
      .comment-item {
        margin-bottom: 30rpx;
        padding-bottom: 20rpx;
        border-bottom: 1px solid #f5f5f5;

        // 评论头部（头像+信息）
        .comment-header {
          display: flex;
          align-items: center;
          margin-bottom: 12rpx;

          .comment-avatar {
            width: 70rpx;
            height: 70rpx;
            border-radius: 20%;
            margin-right: 16rpx;
            background-color: #f5f5f5;
          }

          .comment-meta {
            .comment-name {
              font-size: 26rpx;
              color: #333;
              margin-right: 16rpx;
            }
            .comment-time {
              font-size: 22rpx;
              color: #8a8b8c;
            }
          }
        }

        // 评论内容
        .comment-content {
          margin-left: 78rpx;
          .comment-text {
            font-size: 26rpx;
            color: #343536;
            line-height: 1.6;
          }
        }
      }
    }
  }

}
</style>
